package com.teacold.customdemo.chapter_seven;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class BezierDemo extends View {
    private Paint mPaint;
    private Path mPath;
    private float mPreX,mPreY;

    public BezierDemo(Context context) {
        super(context);
        initView();
    }

    public BezierDemo(Context context, AttributeSet attrs) {
        this(context);
    }

    public BezierDemo(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs);
    }

    private void initView() {
        mPaint = new Paint();
        mPaint.setStrokeWidth(5);
        mPaint.setStyle(Paint.Style.STROKE);
        mPath = new Path();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.WHITE);
        canvas.drawPath(mPath,mPaint);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
//        ordinary(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPath.moveTo(event.getX(), event.getY());
                mPreX=event.getX();
                mPreY=event.getY();
                return true;
            case MotionEvent.ACTION_MOVE:
                float endX=(mPreX+event.getX())/2;
                float endY=(mPreY+event.getY())/2;
                mPath.quadTo(mPreX,mPreY,endX,endY);
                mPreX=event.getX();
                mPreY=event.getY();
                invalidate();
                break;
            default:
                break;
        }

        return super.onTouchEvent(event);
    }


     private void ordinary(MotionEvent event){
         switch (event.getAction()) {
             case MotionEvent.ACTION_DOWN:
                 mPath.moveTo(event.getX(), event.getY());
                 break;
             case MotionEvent.ACTION_MOVE:
                 mPath.lineTo(event.getX(), event.getY());
                 invalidate();
                 break;
             default:
                 break;
         }
     }

    /**
     * 贝济尔曲线简单
     */
    private void drawBezier(Canvas canvas) {
        mPath.moveTo(100, 300);
        mPath.quadTo(200, 200, 300, 300);
        mPath.quadTo(400, 400, 500, 300);
        canvas.drawPath(mPath, mPaint);
    }

}
